package com.ryl.yomall.user.controller;

import com.ryl.yomall.model.common.constant.RedisConst;
import com.ryl.yomall.model.common.result.Result;
import com.ryl.yomall.model.user.UserInfo;
import com.ryl.yomall.user.service.LoginService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Date 21:25
 * @Author ryl
 */
@RestController
@RequestMapping("/api/user/passport")
public class LoginApiController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //1.判断用户名是否
        userInfo=loginService.login(userInfo);
        if(userInfo !=null) {
            Map result =new HashMap<> (  );
            //传递token UUID 36位 4个小横线
            String uuid = UUID.randomUUID ( ).toString ( ).replaceAll ( "-" ,"" );
            result.put ( "token",uuid );
            //传递昵称
            result.put ( "nickName",userInfo.getNickName () );
            //保存redis一份
            redisTemplate.opsForValue ().set ( RedisConst.USER_LOGIN_KEY_PREFIX+uuid ,userInfo.getId ().toString (),15,TimeUnit.DAYS);
            return Result.ok (result);
        }else{
            return Result.fail ().message ( "用户名或密码错误" );
        }

    }
    @PostMapping("/register")
    public Result register(@RequestBody UserInfo userInfo){
        //1.判断用户名是否
        userInfo=loginService.login(userInfo);
        if(userInfo !=null) {
            loginService.register ( userInfo );
            return Result.ok ();
        }else{
            return Result.fail ().message ( "用户名已存在" );
        }
    }

}
